#include <iostream>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

void handler(int signo)
{
    sleep(1);
    int status = 0;
    pid_t pid;
    while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
    {
        if (WIFEXITED(status))
        {
            cout << "子进程" << pid << "正常退出，退出码是" << WEXITSTATUS(status) << endl;
        }
        else if (WIFSIGNALED(status))
        {
            cout << "子进程" << pid << "被信号" << WTERMSIG(status) << "终止!" << endl;
        }
    }
}

int main()
{
    signal(SIGCHLD, SIG_IGN);
    for (int i = 1; i <= 3; ++i)
    {
        pid_t id = fork();
        if (id == 0)
        {
            cout << "子进程" << getpid() << "启动，将休眠" << i << "秒..." << endl;
            sleep(i);
            exit(i);
        }
        else if (id == -1)
        {
            perror("fork error");
            exit(9);
        }
    }
    while(true){
        cout << "父进程" << getpid() << "启动，等待子进程退出..." << endl;
        sleep(1);
    }
    
    return 0;
}